package com.wg.process.cmd;

import org.apache.commons.collections.CollectionUtils;
import org.flowable.bpmn.model.*;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.condition.ConditionUtil;

import java.util.List;

public class FindNextUserTaskNodeCmd implements Command<UserTask> {

    //private Map<String, Object> vars;

    private RepositoryService repositoryService;
    private ExecutionEntity execution;

    private String processDefId;
    /**
     * 返回下一用户节点
     */
    private UserTask nextUserTask;

    public FindNextUserTaskNodeCmd(RepositoryService repositoryService,ExecutionEntity execution,String processDefId) {
        this.repositoryService = repositoryService;
        this.processDefId = processDefId;
        this.execution = execution;
    }

    @Override
    public UserTask execute(CommandContext commandContext) {
        BpmnModel bpmnModel =repositoryService.getBpmnModel(processDefId);
        FlowElement currentNode = bpmnModel.getFlowElement(execution.getActivityId());
        List<SequenceFlow> outgoingFlows = ((FlowNode) currentNode).getOutgoingFlows();
        if (CollectionUtils.isNotEmpty(outgoingFlows)) {
            this.findNextUserTaskNode(outgoingFlows, execution);
        }
        return nextUserTask;
    }

    private void findNextUserTaskNode(List<SequenceFlow> outgoingFlows, ExecutionEntity execution) {
        for (SequenceFlow outgoingFlow : outgoingFlows) {
            if (ConditionUtil.hasTrueCondition(outgoingFlow, execution)) {
                if (outgoingFlow.getTargetFlowElement() instanceof ExclusiveGateway) {
                    //只有排他网关才继续
                    ExclusiveGateway exclusiveGateway = (ExclusiveGateway) outgoingFlow.getTargetFlowElement();
                    findNextUserTaskNode(exclusiveGateway.getOutgoingFlows(), execution);
                } else if (outgoingFlow.getTargetFlowElement() instanceof UserTask) {
                    nextUserTask = (UserTask) outgoingFlow.getTargetFlowElement();
                    //找到第一个符合条件的userTask就跳出循环
                    break;
                }
            }
        }
    }

}
